/**
 * Created by 游永年 on 2019-01-12 01:42.
 * 首页轮播图
 */
'use strict'
import {Carousel} from 'antd-mobile';
import {connect} from "dva/index";
import React, {Component} from 'react';

class HomeCarousel extends Component {
  state = {
    data: ['1', '2', '3'],
    imgHeight: 176,
    play: false,
  }

  UNSAFE_componentWillMount() {
    if (this.props.data.length === 0) this.props.dispatch({type: 'home/fetchBanner'});
    this.timeout = setTimeout(_ => this.setState({play: true}), 0);
  }

  render() {
    return (
      <Carousel
        autoplay={this.state.play}
        autoplayInterval={2000}
        infinite
        // beforeChange={(from, to) => console.log(`slide from ${from} to ${to}`)}
        // afterChange={index => console.log('slide to', index)}
        style={{width: document.body.clientWidth}}
      >
        {this.props.data.map(({img, link, orderid}) => (
          <a
            key={orderid}
            href={link}
            style={{display: 'inline-block', width: '100%', height: this.state.imgHeight}}
          >
            <img
              src={img}
              alt=""
              style={{width: '100%', verticalAlign: 'top'}}
              onLoad={() => {
                window.dispatchEvent(new Event('resize'));
                this.setState({imgHeight: 'auto'});
              }}
            />
          </a>
        ))}
      </Carousel>
    );
  }
}

HomeCarousel.propTypes = {}

const opts = ({home}) => {
  const {banners = []} = home || {};
  return {data: banners};
};

export default connect(opts)(HomeCarousel);
